<template>
  <el-form ref="formRef" :model="password" :rules="rules" :label-width="100">
    <el-alert class="!mb-[15px]" type="warning" :closable="false">
      {{ t('profile.localPassword.tips', { phone: userStore.getAccount.phone }) }}
    </el-alert>

    <el-form-item :label="t('profile.localPassword.code')" prop="code">
      <div class="flex gap-[10px]">
        <el-input v-model="password.code" style="width: 190px" />
        <el-button type="primary" plain @click="handleSendSmsCode">
          {{ t('profile.localPassword.sendCode') }}
        </el-button>
      </div>
    </el-form-item>
    <el-form-item :label="t('profile.localPassword.newPassword')" prop="newPassword">
      <InputPassword v-model="password.newPassword" strength />
    </el-form-item>
    <el-form-item :label="t('profile.localPassword.confirmPassword')" prop="confirmPassword">
      <InputPassword v-model="password.confirmPassword" strength />
    </el-form-item>
    <el-form-item>
      <XButton :title="t('common.save')" type="primary" @click="submit(formRef)" />
      <XButton :title="t('common.reset')" type="danger" @click="reset(formRef)" />
    </el-form-item>
  </el-form>

  <Verify
    ref="resetSmsRef"
    :captchaType="captchaType"
    :imgSize="{ width: '400px', height: '200px' }"
    mode="pop"
    @success="handleSendResetSms"
  />
</template>
<script lang="ts" setup>
import { ElLoading, FormInstance, FormRules } from 'element-plus'

import * as LoginApi from '@/api/login'
import { InputPassword } from '@/components/InputPassword'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'ModifyUstcLocalPwd' })
const userStore = useUserStore()
const { replace } = useRouter()

const { t } = useI18n()
const message = useMessage()
const formRef = ref<FormInstance>()
const password = reactive({
  code: '',
  newPassword: '',
  confirmPassword: ''
})
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

// 表单校验
const equalToPassword = (_rule, value, callback) => {
  if (password.newPassword !== value) {
    callback(new Error(t('profile.localPassword.diffPwd')))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  code: [
    { required: true, message: t('profile.localPassword.codeMsg'), trigger: 'blur' },
    { min: 6, max: 6, message: t('profile.localPassword.codeRules'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('profile.localPassword.newPwdMsg'), trigger: 'blur' },
    { min: 6, max: 20, message: t('profile.localPassword.pwdRules'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('profile.localPassword.cfPwdMsg'), trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await LoginApi.resetUstcLocalPassword({
        password: password.newPassword,
        code: password.code
      })
      message.success(t('profile.localPassword.modifySuccess'))
      emit('success')
    }
  })
}
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// step1: 点击按钮弹出拉杆验证码
const resetSmsRef = ref()
const handleSendSmsCode = () => {
  resetSmsRef.value?.show()
}

const loading = ref() // ElLoading.service 返回的实例
// step2: 滑动验证后 弹出输入验证码和新密码的窗口
const handleSendResetSms = async (params) => {
  loading.value = ElLoading.service({
    lock: true,
    text: t('resetPwd.smsSending'),
    background: 'rgba(0, 0, 0, 0.7)'
  } as any)
  try {
    const res = await LoginApi.sendResetLocalPasswordSmsToUstcAccount({
      captchaVerification: params.captchaVerification
    })
    if (!res) {
      return
    }
    //
    message.success(t('resetPwd.smsSendTo', { phone: res }))
  } finally {
    loading.value?.close()
  }
}
</script>
